<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item> <i class="el-icon-setting"></i> 人员管理 </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-row :gutter="10">
      <el-col :span="5" class="container" v-loading="B_OBJECT.infoLaod">
        <el-tree :data="data" :props="defaultProps" node-key="id" default-expand-all :expand-on-click-node="false" @node-click="handleNodeClick">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span>
              <el-button v-if="threeLevelsbool.add" type="text" size="mini" icon="el-icon-plus" @click="() => append(data)"></el-button>
              <el-button v-if="threeLevelsbool.edit" type="text" size="mini" icon="el-icon-edit" @click="() => editClick(data)"></el-button>
              <el-button v-if="threeLevelsbool.del" type="text" size="mini" icon="el-icon-delete" @click="() => remove(node, data)"></el-button>
            </span>
          </span>
        </el-tree>
      </el-col>
      <el-col :span="19">
        <div class="container" v-loading="loading">
          <el-breadcrumb separator="/" style="margin-bottom: 15px">
            <el-breadcrumb-item>
              <i class="el-icon-setting"></i> {{ B_OBJECT.B_OBJECT_addeditremove.label }}
            </el-breadcrumb-item>
          </el-breadcrumb>
          <div class="handle-box">
            <el-button v-if="threeLevelsbool.addName" type="primary" class="handle-del mr10" @click="addTable">新增</el-button>
            <el-input v-model="query.kw" placeholder="请输入用户名/电话进行搜索" class="handle-input mr10"></el-input>
            <el-button type="primary" icon="el-icon-search" @click="getData(B_OBJECT.B_OBJECT_addeditremove.value)">搜索</el-button>
          </div>
          <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column type="index" :index="tableIndex" label="序号" align="center" width="55"></el-table-column>
            <el-table-column prop="userName" label="用户名"></el-table-column>
            <el-table-column prop="name" label="姓名" width="150"></el-table-column>
            <el-table-column label="电话" width="150">
              <template slot-scope="scope">{{ scope.row.phone }}</template>
            </el-table-column>
            <el-table-column prop="roleNames" label="身份" width="150"></el-table-column>
            <el-table-column prop="departments" label="所属部门" width="200"></el-table-column>
            <el-table-column prop="createTime" label="录入时间" width="200"></el-table-column>
            <el-table-column fixed="right" label="坐席状态" align="center" width="80">
              <template slot-scope="scope">
                <el-tag :type="scope.row.extParam2 == '1' ? 'success' : 'danger'">{{
                                    scope.row.extParam2 == '1' ? '开启' : '关闭'
                                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="账号状态" align="center" width="80">
              <template slot-scope="scope">
                <el-tag :type="scope.row.isJob === '1' ? 'success' : 'danger'">{{
                                    scope.row.isJob === '1' ? '在职' : '离职'
                                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="150" align="center">
              <template slot-scope="scope">
                <el-button v-if="threeLevelsbool.editName" type="text" icon="el-icon-edit" @click="handleEdit(scope.row.id)">编辑</el-button>
                <el-button v-if="threeLevelsbool.removeName" type="text" icon="el-icon-delete" class="red" @click="delList(scope.row.id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination background layout="total, prev, pager, next" :current-page="query.page" :page-size="query.limit" :total="totalCount"
                           :pager-count="5" @current-change="handlePageChange" @prev-click="handlePageChange" @next-click="handlePageChange">
            </el-pagination>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 编辑部门弹窗 -->
    <el-dialog title="编辑部门" :visible.sync="B_OBJECT.addDialogFlg" width="30%" :close-on-click-modal="false">
      <el-form ref="form" label-width="70px" v-loading="B_OBJECT.addDialogLoad">
        <el-form-item label="部门名称">
          <el-input v-model="B_OBJECT.name"></el-input>
        </el-form-item>
        <el-form-item label="所属区域" v-if="cityDataFlg">
          <el-cascader v-model="B_OBJECT.citycode" :options="cityData" @change="citycode" style="width:100%;"></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="B_OBJECT.addDialogFlg = false">取 消</el-button>
        <el-button v-if="B_OBJECT.flg == 'add'" type="primary" @click="addendSubAjax()">确 定</el-button>
        <el-button v-else type="primary" @click="editClickSub()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 删除部门弹窗 -->
    <el-dialog title="删除部门" :visible.sync="B_OBJECT.removeFlg" width="30%" :close-on-click-modal="false">
      <el-form ref="form" label-width="0" v-loading="B_OBJECT.removeLoad">
        <div style="font-size: 14px; margin-bottom: 10px">
          <span style="color: red">*</span> 将该部门下的人员迁移到以下哪个同级部门下
        </div>
        <el-form-item label="">
          <el-radio-group v-model="B_OBJECT.radioList">
            <el-radio label="销售三部"></el-radio>
            <el-radio label="销售六部"></el-radio>
            <el-radio label="华北区销冠部"></el-radio>
            <el-radio label="划水部门"></el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="B_OBJECT.removeFlg = false">取 消</el-button>
        <el-button type="primary" @click="saveEditAdd()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑弹出框 -->
    <el-dialog title="基本信息" :visible.sync="editVisible" width="30%" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="form" label-width="120px" v-loading="addloading">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input type="number" v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input type="password" v-model="form.pwd" :show-password="true"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="isJob">
          <el-radio-group v-model="form.isJob">
            <el-radio label="1">在职</el-radio>
            <el-radio label="0">离职</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="坐席邮箱" prop="extParam5">
          <el-input v-model="form.extParam5" placeholder="xxxxxx@xxx.com"></el-input>
        </el-form-item>
        <el-form-item label="是否使用坐席" prop="">
          <el-switch style="margin-left:10px;" v-model="form.extParam2" active-value="1" active-color="#13ce66" active-text="开启" inactive-value="0"
                     inactive-color="#ff4949" inactive-text="关闭">
          </el-switch>
        </el-form-item>
        <el-form-item label="同步企业微信" prop="">
          <el-switch style="margin-left:10px;" v-model="form.value" active-value="0" active-color="#13ce66" active-text="同步" inactive-value="1"
                     inactive-color="#ff4949" inactive-text="不同步">
          </el-switch>
        </el-form-item>

        <template v-for="(item, i) in BumenShenArr">
          <el-form-item label="部门">
            <el-cascader v-model="item.BumenSelected" :options="data" :props="{ checkStrictly: true }" @change="buMenChange(item, i)"
                         :style="i > 0 ? 'width:88%;' : 'width:100%;'"></el-cascader>
            <el-button v-if="i > 0" type="danger" icon="el-icon-delete" circle style="float: right" @click="removeShenMen(i)"></el-button>
          </el-form-item>
          <el-form-item label="身份">
            <el-select v-model="item.roleId" placeholder="请选择身份">
              <el-option v-for="(item, index) in item.identityArr" :label="item.roleName" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </template>

        <el-form-item label="">
          <el-button type="text" @click="addShenMen">+ 新增部门身份</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditAdd('form', editID)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  PersonnelBUInfo,
  PersonnelBUAdd,
  PersonnelBUEdit,
  PersonnelLists,
  PersonnelBumenIdentity,
  PersonnelIdentity,
  PersonnelAddAjaxSub,
  PersonneldelAjax,
  PersonneleditAjax,
  PersonneleditAjaxSub,
  RolePermissionsQX,
  PersonnelBURemove,
  idHome,
} from '../../../api/index';
import cityData from '../../../utils/city'
export default {
  data() {
    return {
      cityData: [],
      cityDataFlg: false,
      //部门
      data: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      B_OBJECT: {
        infoLaod: true,
        addDialogFlg: false,
        addDialogLoad: false,
        name: '',
        citycode: [],
        citycodeval: '',
        removeFlg: false,
        removeLoad: false,
        radioList: [],
        flg: '',
        //部门操作保存当前操作id
        B_OBJECT_addeditremove: ''
      },

      //列表加载
      loading: true,
      //新增编辑状态
      editVisible: false,
      //初始化列表参数
      query: {
        page: 1,
        limit: 10,
        kw: '',
        teamId: ''
      },
      tableData: [],
      totalCount: 0,
      totalPage: 0,

      addloading: false,
      BumenShenArr: [
        {
          roleId: '',
          BumenSelected: [],
          identityArr: []
        }
      ],
      editID: '',
      form: {
        name: '',
        userName: '',
        phone: '',
        pwd: '',
        isJob: '1',
        extParam5: '',
        extParam2: '0',
      },
      rules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        userName: [{ required: true, message: '请输入用户名称', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
        pwd: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        isJob: [{ required: true, message: '请输入职位', trigger: 'change' }]
      },
      multipleSelection: [],

      threeLevelsbool: {
        add: false,
        edit: false,
        del: false,
        addName: false,
        editName: false,
        removeName: false
      }
    };
  },
  created() {
    this.threeLevels();
    this.BUInfo();
    //整理城市数据
    cityData.forEach((item, index) => {
      this.cityData.push({
        label: item.label,
        value: item.value
      })
      if (item.children) {
        this.cityData[index].children = [];
        item.children.forEach((e, i) => {
          this.cityData[index].children.push({
            label: e.label,
            value: e.value + "-" + e.code
          })
        })
      }
    })
  },
  watch: {
    $route: 'getData',
    //关闭弹窗清除编辑状态
    editVisible: function(n) {
      if (!n) {
        this.editID = '';
        this.$refs.form.resetFields();
      }
    }
  },
  methods: {
    //初始化部门
    BUInfo() {
      PersonnelBUInfo()
        .then((res) => {
          this.data = [];
          let index = 0;
          this.B_OBJECT.infoLaod = false;
          if (res.code === 0 && res.teamList.length > 0) {
            res.teamList.forEach((item, i) => {
              this.data.push({
                label: item.name,
                value: item.id,
                code: item.tCityCode,
                index: index
              });
              this.BUInfoDataFor(item.childTeam, this.data[i], index);
            });
            this.getData(this.data[0].value);
            this.B_OBJECT.B_OBJECT_addeditremove = this.data[0];
          } else {
            this.$message(res.msg);
          }
        })
        .catch((res) => {
          console.log(res);
        });
    },
    //初始化部门下级循环
    BUInfoDataFor(item, arr, index) {
      if (item.length > 0) {
        index++;
        arr.children = [];
        item.forEach((e, i) => {
          arr.children.push({
            label: e.name,
            value: e.id,
            code: e.tCityCode,
            index: index
          });
          this.BUInfoDataFor(e.childTeam, arr.children[i], index);
        });
      }
    },
    //添加部门
    append(data) {
      if (data.index == 0) {
        this.cityDataFlg = true;
      } else {
        this.cityDataFlg = false;
      }
      this.B_OBJECT.addDialogFlg = true;
      this.B_OBJECT.name = '';
      this.B_OBJECT.citycode = [];
      this.B_OBJECT.addDialogLoad = false;
      this.B_OBJECT.flg = 'add';
      this.B_OBJECT.B_OBJECT_addeditremove = data;
    },
    //选中部门所属城市
    citycode(val) {
      this.B_OBJECT.citycodeval = val[1].split("-")[1];
    },
    //添加部门提交
    addendSubAjax() {
      this.B_OBJECT.addDialogLoad = true;
      let obj = {
        parentId: this.B_OBJECT.B_OBJECT_addeditremove.value,
        teamName: this.B_OBJECT.name,
        cityCode: this.B_OBJECT.citycodeval
      };
      PersonnelBUAdd(obj).then((res) => {
        this.B_OBJECT.addDialogLoad = false;
        if (res.code === 0) {
          this.$message.success('创建成功');
          this.B_OBJECT.addDialogFlg = false;
          this.BUInfo();
        } else {
          this.$message(res.msg);
        }
      });
    },
    //编辑部门
    editClick(data) {
      this.B_OBJECT.citycode = [];
      if (data.code) {
        this.cityData.forEach((item, index) => {
          item.children.forEach((e, i) => {
            if (e.value.split("-")[1] == data.code) {
              this.B_OBJECT.citycode = [item.value, e.value];
            }
          })
        })
      }
      if (data.index == 1) {
        this.cityDataFlg = true;
      } else {
        this.cityDataFlg = false;
      }
      this.B_OBJECT.addDialogFlg = true;
      this.B_OBJECT.addDialogLoad = false;
      this.B_OBJECT.flg = 'edit';
      this.B_OBJECT.B_OBJECT_addeditremove = data;
      this.B_OBJECT.name = data.label;
    },
    //编辑部门提交
    editClickSub() {
      this.B_OBJECT.addDialogLoad = true;
      let obj = {
        teamId: this.B_OBJECT.B_OBJECT_addeditremove.value,
        teamName: this.B_OBJECT.name,
        cityCode: this.B_OBJECT.citycodeval
      };
      PersonnelBUEdit(obj).then((res) => {
        this.B_OBJECT.addDialogLoad = false;
        if (res.code === 0) {
          this.$message.success('编辑成功');
          this.B_OBJECT.addDialogFlg = false;
          this.BUInfo();
        } else {
          this.$message(res.msg);
        }
      });
    },
    //删除部门
    remove(node, data) {
      this.cityDataFlg = false;
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          // this.B_OBJECT.removeFlg = true;
          PersonnelBURemove({ teamId: data.value }).then((res) => {
            this.B_OBJECT.addDialogLoad = false;
            if (res.code === 0) {
              this.$message.success('删除成功');
              this.B_OBJECT.addDialogFlg = false;
              this.BUInfo();
            } else {
              this.$message(res.msg);
            }
          });

        })
        .catch(() => { });
    },
    //点击部门
    handleNodeClick(data) {
      this.loading = true;
      this.B_OBJECT.B_OBJECT_addeditremove = data;
      this.getData(data.value);
    },
    // 获取人员
    getData(id) {
      this.query.teamId = id;
      PersonnelLists(this.query).then((res) => {
        this.loading = false;
        if (res.code === 0) {
          res.userList.forEach((item, i) => {
            item.roleNames = item.roleNames.join(' , ');
            item.departments = item.departments.join(' , ');
          });
          this.tableData = res.userList;
          this.totalCount = res.totalCount;
          this.totalPage = res.totalPage;
        } else {
          this.$message(res.msg);
        }
      });
    },
    //序号
    tableIndex(index) {
      return (this.query.page - 1) * this.query.limit + index + 1;
    },
    // 分页切换
    handlePageChange(val) {
      this.loading = true;
      this.$set(this.query, 'page', val);
      this.getData(this.B_OBJECT.B_OBJECT_addeditremove.value);
    },
    //新增身份获取
    addTable() {
      this.editVisible = true;
      this.addloading = true;
      let id = this.B_OBJECT.B_OBJECT_addeditremove.value;
      this.BumenShenArr = [{ roleId: '', BumenSelected: [], identityArr: [] }];
      PersonnelBumenIdentity({ teamId: id }).then((res) => {
        this.addloading = false;
        if (res.code === 0) {
          this.BumenShenArr[0].identityArr = res.roleList;
          this.BumenShenArr[0].BumenSelected = res.teamIds;
        } else {
          this.$message(res.msg);
        }
      });
    },
    //切换部门获取对应身份
    buMenChange(data, i) {
      let id = data.BumenSelected[data.BumenSelected.length - 1];
      PersonnelBumenIdentity({ teamId: id }).then((res) => {
        this.addloading = false;
        if (res.code === 0) {
          this.BumenShenArr[i].identityArr = res.roleList;
          this.BumenShenArr[i].roleId = '';
        } else {
          this.$message(res.msg);
        }
      });
    },
    //增加部门身份
    addShenMen() {
      this.BumenShenArr.push({ roleId: '', BumenSelected: [], identityArr: [] });
    },
    //删除部门身份
    removeShenMen(i) {
      this.BumenShenArr.splice(i, 1);
    },
    //新增编辑提交前验证
    saveEditAdd(formName, id) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addloading = true;
          if (id) {
            this.handleEditSub(id);
          } else {
            this.saveEditAddSub();
          }
        } else {
          // console.log(res.msg);
          return false;
        }
      });
    },
    //编辑查询
    handleEdit(id) {
      this.addTable();
      this.addloading = true;
      this.editID = id;
      PersonneleditAjax({ userId: id }).then((res) => {
        if (res.code === 0) {
          this.addloading = false;
          this.form.name = res.userInfoResponse.user.name;
          this.form.userName = res.userInfoResponse.user.userName;
          this.form.phone = res.userInfoResponse.user.phone;
          this.form.pwd = res.userInfoResponse.user.pwd;
          this.form.job = res.userInfoResponse.user.job;
          this.form.isJob = res.userInfoResponse.user.isJob;
          this.form.extParam2 = String(res.userInfoResponse.user.extParam2);
          this.form.extParam5 = res.userInfoResponse.user.extParam5;
          //处理部门选中数据
          this.handleEditdata(res.userInfoResponse.teamAndRole);
        } else {
          this.$message(res.msg);
        }
      });
    },
    //编辑查询时部门数据整理赋值
    handleEditdata(arr) {
      let dataArr = [];
      this.BumenShenArr = [];
      arr.forEach((item, i) => {
        this.BumenShenArr.push({
          roleId: item.roleId,
          BumenSelected: "",
          identityArr: item.roles
        });
        this.idpostion(item.teamId, this.BumenShenArr[i]);
      });
    },
    //id定位多维
    idpostion(id, item) {
      idHome({ targetId: id, findTeamList: this.data }).then((res) => {
        if (res.code === 0) {
          item.BumenSelected = res.route;
        }
      })
    },
    // 新增提交
    saveEditAddSub() {
      let that = this;
      let obj = {
        user: this.form,
        teamAndRoleParamList: (() => {
          let arr = [];
          that.BumenShenArr.forEach((item, i) => {
            arr.push({
              roleId: item.roleId,
              teamId: item.BumenSelected[item.BumenSelected.length - 1],
              teamArr: JSON.stringify(item.BumenSelected)
            });
          });
          return arr;
        })()
      };
      PersonnelAddAjaxSub(obj).then((res) => {
        this.addloading = false;
        if (res.code === 0) {
          this.loading = true;
          this.editVisible = false;
          this.$message.success('新增成功');
          this.getData(this.B_OBJECT.B_OBJECT_addeditremove.value);
        } else {
          this.$message(res.msg);
        }
      });
    },
    //编辑提交
    handleEditSub(id) {
      this.form.id = id;
      let that = this;
      let obj = {
        user: this.form,
        teamAndRoleParamList: (() => {
          let arr = [];
          that.BumenShenArr.forEach((item, i) => {
            arr.push({
              roleId: item.roleId,
              teamId: item.BumenSelected[item.BumenSelected.length - 1],
              teamArr: JSON.stringify(item.BumenSelected)
            });
          });
          return arr;
        })()
      };
      PersonneleditAjaxSub(obj).then((res) => {
        this.addloading = false;
        if (res.code === 0) {
          this.loading = true;
          this.editVisible = false;
          this.$message.success('编辑成功');
          this.getData(this.B_OBJECT.B_OBJECT_addeditremove.value);
        } else {
          this.$message(res.msg);
        }
      });
    },
    //删除
    delList(id) {
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.loading = true;
          PersonneldelAjax({ userId: id }).then((res) => {
            if (res.code === 0) {
              this.$message.success('删除成功');
              this.getData(this.B_OBJECT.B_OBJECT_addeditremove.value);
            } else {
              this.loading = false;
              this.$message(res.msg);
            }
          });
        })
        .catch(() => { });
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = [];
      val.forEach((item, i) => {
        this.multipleSelection.push(item.id);
      });
    },
    //三级权限
    threeLevels() {
      let parentRouth = this.$route.path.replace('/', '');
      RolePermissionsQX({ urlName: parentRouth }).then((res) => {
        if (res.code === 0) {
          res.buttons.forEach((item, i) => {
            switch (item.name) {
              case '新增部门':
                this.threeLevelsbool.add = item.pageIsShow;
                break;
              case '编辑部门':
                this.threeLevelsbool.edit = item.pageIsShow;
                break;
              case '删除部门':
                this.threeLevelsbool.del = item.pageIsShow;
                break;
              case '新增人员':
                this.threeLevelsbool.addName = item.pageIsShow;
                break;
              case '编辑人员':
                this.threeLevelsbool.editName = item.pageIsShow;
                break;
              case '删除人员':
                this.threeLevelsbool.removeName = item.pageIsShow;
                break;
            }
          });
        } else {
          this.$message(res.msg);
        }
      });
    }
  }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.el-select {
    width: 100%;
}
.con-left {
    padding: 0 10px;
    font-size: 14px;
    color: #606266;
}
.con-left li {
    overflow: hidden;
    border-bottom: 1px solid #ebeef5;
    line-height: 32px;
}
.con-left button {
    float: right;
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}

.el-radio {
    line-height: 1.7;
}
</style>
